package admin.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.StoreItemModel;
import models.TransactionModel;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.googlecode.objectify.annotation.Cached;

@Cached
public class TransactionData {

	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "Transaction_";

	public TransactionData() {
		try {
			ObjectifyService.register(TransactionModel.class);
		} catch (Exception e) {
			// TODO: handle exception
		}

		try {
			cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e) {
			// e.printStackTrace();
		}

		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public void insert(TransactionModel transaction) {
		ofy.put(transaction);
	} 
	
	public List<TransactionModel> getList(String storeItemId)
	{
		List<TransactionModel> list = new ArrayList<TransactionModel>();
		Query<TransactionModel> q = ofy.query(TransactionModel.class).filter("storeItemId", storeItemId).order("-date");
		for (TransactionModel transaction : q) {
			list.add(transaction);
		}	
		return list;
	}
}
